<script setup lang="ts">
import { reactive, ref, onUnmounted, computed } from 'vue';
import { ElForm, ElFormItem, ElInput, ElButton, ElLink, ElMessage, ElLoading, ElCheckbox } from 'element-plus';
import type { FormInstance, FormRules } from 'element-plus';
import { useRouter } from 'vue-router';

// 注册表单数据
const registerForm = reactive({
  phone: '',
  code: '',
  password: '',
  confirmPassword: '',
  agreement: false
});

// 表单验证规则
const formRules: FormRules = {
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { pattern: /^\d{6}$/, message: '请输入6位数字验证码', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请设置密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度必须在6-20位之间', trigger: 'blur' },
    { pattern: /^(?=.*[a-zA-Z])(?=.*\d).+$/, message: '密码必须包含字母和数字', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== registerForm.password) {
          callback(new Error('两次输入的密码不一致'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  agreement: [
    {
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error('请同意用户协议和隐私政策'));
        } else {
          callback();
        }
      },
      trigger: 'change'
    }
  ]
};

// 表单引用
const formRef = ref<FormInstance>();
// 倒计时控制
const countdown = ref(0);
// 定时器
let timer: any = null;
// 路由实例
const router = useRouter();
// 密码强度
const passwordStrength = ref<0 | 1 | 2 | 3>(0); // 0:未设置 1:弱 2:中 3:强

// 密码强度样式类
const strengthClass = computed(() => {
  const classes = ['', '', ''];
  if (passwordStrength.value >= 1) classes[0] = 'weak';
  if (passwordStrength.value >= 2) classes[1] = 'medium';
  if (passwordStrength.value >= 3) classes[2] = 'strong';
  return classes;
});

// 组件卸载时清除定时器
onUnmounted(() => {
  if (timer) {
    clearInterval(timer);
  }
});

// 切换到登录页面
const switchToLogin = () => {
  router.push('/Register').catch(err => console.error('跳转失败:', err));
};

// 检查密码强度
const checkPasswordStrength = (value: string) => {
  let strength = 0;

  // 基础长度检查
  if (value.length >= 6) strength++;
  if (value.length >= 12) strength++;

  // 复杂度检查
  if (/[A-Z]/.test(value) && /[a-z]/.test(value)) strength++; // 包含大小写字母
  if (/[^A-Za-z0-9]/.test(value)) strength++; // 包含特殊字符

  // 限制最大值为3
  passwordStrength.value = Math.min(strength, 3) as 0 | 1 | 2 | 3;
};

// 获取验证码（适配/SmsSend接口）
const getVerificationCode = async () => {
  // 先验证手机号格式
  if (!formRef.value) return;

  try {
    await formRef.value.validateField('phone');

    // 显示加载状态
    const loading = ElLoading.service({
      lock: false,
      text: '发送中...',
      target: '.get-code-btn'
    });

    // 调用后端/SmsSend接口（GET方式）
    const response = await fetch(`http://localhost:8020/SmsSend?mobile=${registerForm.phone}`);
    const result = await response.json();

    loading.close();

    if (result.success) {
      ElMessage.success('验证码已发送，请注意查收（3分钟内有效）');
      // 开始倒计时
      startCountdown();
    } else {
      ElMessage.error(result.message || '验证码发送失败');
    }
  } catch (error) {
    console.error('发送验证码错误:', error);
    ElMessage.error('获取验证码失败，请重试');
  }
};

// 开始倒计时
const startCountdown = () => {
  countdown.value = 60;
  if (timer) clearInterval(timer);

  timer = setInterval(() => {
    countdown.value--;
    if (countdown.value <= 0) {
      clearInterval(timer);
      timer = null;
    }
  }, 1000);
};

// 处理注册逻辑（先验证验证码，再调用注册接口）
const handleRegister = async () => {
  // 表单校验
  if (!formRef.value) return;

  try {
    await formRef.value.validate();

    // 显示加载状态
    const loading = ElLoading.service({
      lock: true,
      text: '注册中...',
      background: 'rgba(0, 0, 0, 0.7)'
    });

    // 1. 先调用/SmsVerify接口验证验证码
    const verifyResponse = await fetch(
        `http://localhost:8020/SmsVerify?mobile=${registerForm.phone}&code=${registerForm.code}`
    );
    const verifyResult = await verifyResponse.json();

    if (!verifyResult.success) {
      loading.close();
      ElMessage.error(verifyResult.message || '验证码错误或已过期');
      return;
    }

    // 2. 验证码通过后，调用注册接口
    const registerData = {
      phone: registerForm.phone,
      password: registerForm.password
    };

    const response = await fetch('http://localhost:8020/user/Register', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(registerData)
    });

    const result = await response.json();
    loading.close();

    // 处理注册结果
    if (result.code === 0) {
      // 从响应头获取token并存储
      const token = response.headers.get('Authorization')?.replace('Bearer ', '');
      if (token) {
        localStorage.setItem('token', token);
        ElMessage.success('注册成功，已自动登录');
      } else {
        ElMessage.success('注册成功，即将跳转到登录页');
      }

      // 延迟跳转，让用户看到成功提示
      setTimeout(() => {
        router.push('/login').catch(err => console.error('跳转失败:', err));
      }, 1500);
    } else {
      ElMessage.error(result.msg || '注册失败，请重试');
    }
  } catch (error) {
    console.error('注册请求错误:', error);
    ElMessage.error('注册失败，请检查网络或联系管理员');
  }
};
</script>

<template>
  <div class="register-container">
    <el-form
        ref="formRef"
        :model="registerForm"
        :rules="formRules"
        label-width="80px"
        class="register-form"
    >
      <h2 class="register-title">用户注册</h2>

      <el-form-item label="手机号" prop="phone">
        <el-input
            v-model="registerForm.phone"
            placeholder="请输入手机号"
            prefix-icon="el-icon-phone"
            maxlength="11"
            clearable
        />
      </el-form-item>

      <el-form-item label="验证码" prop="code">
        <el-row :gutter="10">
          <el-col :span="14">
            <el-input
                v-model="registerForm.code"
                placeholder="请输入验证码"
                prefix-icon="el-icon-key"
                maxlength="6"
                clearable
            />
          </el-col>
          <el-col :span="10">
            <el-button
                type="default"
                class="get-code-btn"
                @click="getVerificationCode"
                :disabled="countdown > 0"
            >
              {{ countdown > 0 ? `${countdown}s后重新获取` : '获取验证码' }}
            </el-button>
          </el-col>
        </el-row>
      </el-form-item>

      <el-form-item label="密码" prop="password">
        <el-input
            v-model="registerForm.password"
            type="password"
            placeholder="请设置密码（6-20位，含字母和数字）"
            prefix-icon="el-icon-lock"
            show-password
            @input="checkPasswordStrength"
        />
        <!-- 密码强度提示 -->
        <div class="password-strength" v-if="registerForm.password">
          <div class="strength-labels">
            <span :class="['strength-item', strengthClass[0]]">弱</span>
            <span :class="['strength-item', strengthClass[1]]">中</span>
            <span :class="['strength-item', strengthClass[2]]">强</span>
          </div>
        </div>
      </el-form-item>

      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input
            v-model="registerForm.confirmPassword"
            type="password"
            placeholder="请再次输入密码"
            prefix-icon="el-icon-lock"
            show-password
        />
      </el-form-item>

      <el-form-item prop="agreement">
        <el-checkbox v-model="registerForm.agreement">
          我已阅读并同意
          <el-link type="primary">用户协议</el-link>和
          <el-link type="primary">隐私政策</el-link>
        </el-checkbox>
      </el-form-item>

      <el-form-item>
        <el-button
            type="primary"
            class="register-btn"
            @click="handleRegister"
            style="background: #00C853"
        >
          注册
        </el-button>
      </el-form-item>

      <div class="extra-links">
        <el-link type="primary" @click="switchToLogin">已有账号？去登录</el-link>
      </div>
    </el-form>
  </div>
</template>

<style scoped>
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f7fa;
  padding: 20px;
}

.register-form {
  width: 100%;
  max-width: 360px;
  background-color: #fff;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.register-title {
  text-align: center;
  margin-bottom: 20px;
  font-size: 1.2rem;
  font-weight: 600;
  color: #333;
}

.register-btn, .get-code-btn {
  width: 100%;
}

.extra-links {
  text-align: center;
  margin-top: 15px;
  font-size: 14px;
}

/* 密码强度样式 */
.password-strength {
  margin-top: 8px;
}

.strength-labels {
  display: flex;
  gap: 4px;
}

.strength-item {
  flex: 1;
  text-align: center;
  font-size: 12px;
  padding: 2px 0;
  border-radius: 4px;
  color: #fff;
  background-color: #ddd;
  transition: background-color 0.3s ease;
}

.strength-item.weak {
  background-color: #ff4d4f;
}

.strength-item.medium {
  background-color: #faad14;
}

.strength-item.strong {
  background-color: #52c41a;
}

/* 适配移动端 */
@media (max-width: 480px) {
  .register-form {
    padding: 16px;
  }

  .register-title {
    font-size: 1rem;
    margin-bottom: 16px;
  }
}
</style>